<template>
	<div class="supplier-billing">
		<h3 style="margin: 0;margin-bottom: 20px;">
			{{ supplier.suppliersName }}
		</h3>
		<div style="display: flex;justify-content: space-between;">
			<div style="display: flex;">
				<el-button type="primary" plain @click="toBack">返回</el-button>
				<div style="margin-left: 20px; line-height: 40px;">
					<el-radio v-model="radio" :label="1" @input="radioChange">
						月结账单
					</el-radio>
					<el-radio v-model="radio" :label="0" @input="radioChange">
						历史账单
					</el-radio>
				</div>
			</div>
			<div>
				<div v-if="userInfo.roleId === '1'" style="line-height: 40px;display: inline-block;margin-right: 10px">
					<span>总计金额：{{ MtotalAmount }}</span>
				</div>
				<el-date-picker v-model="selectDate" type="month" placeholder="选择日期" @change="changeDate"
					:clearable="false" v-if="radio === 0">
				</el-date-picker>
				<el-button @click="reset" style="margin-left: 10px;" v-if="radio === 0">
					重置
				</el-button>
				<el-button type="primary" @click="paymentDialog" v-if="true">
					付款
				</el-button>
			</div>
		</div>
		<!-- 历史账单 -->
		<div class="data-table">
			<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%" height="100%"
				:row-key="(row) => row.id" @selection-change="handleSelectionChange" ref="multipleTable">
        <el-table-column v-if="true" :selectable="selectable" type="selection" :reserve-selection="true"
					width="40">
				</el-table-column>
				<el-table-column prop="i" label="序号" width="60">
				</el-table-column>
				<el-table-column prop="userName" label="采购人" width="120">
				</el-table-column>
				<el-table-column label="零件列表" width="100">
					<template slot-scope="scope">
						<el-button type="text" @click="partsOpen(scope.row)">点击查看</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="price" label="总金额" width="80">
				</el-table-column>
				<el-table-column prop="orderTime" label="下单时间" width="160">
				</el-table-column>
				<el-table-column prop="amountPayable" label="付款金额" width="80">
				</el-table-column>
				<el-table-column prop="datePayable" label="付款日期" width="120">
				</el-table-column>
				<el-table-column prop="paymentAmount" label="实付金额" width="80">
				</el-table-column>
				<el-table-column prop="paymentDate" label="实付日期" width="160">
				</el-table-column>
				<el-table-column prop="account" label="付款账户" width="220">
				</el-table-column>
				<el-table-column label="账单状态" width="100" fixed="right">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.billsStatus === 0" type="warning">
							待付款
						</el-tag>
						<el-tag v-if="scope.row.billsStatus === 1" type="success">
							已付款
						</el-tag>
						<el-tag v-if="scope.row.billsStatus === 2" type="danger">
							已逾期
						</el-tag>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background v-if="radio === 0" @size-change="handleSizeChange"
				@current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 50, 100]"
				:page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
		<!-- 查看零件列表弹窗 -->
		<el-dialog style="margin-top:0" :visible.sync="partsShow" width="75%" :title="selectTitle" @close="partsClose">
			<div class="data-table">
				<el-table :data="selectPurchase.parts" border stripe style="width: 100%" :max-height="500">
					<el-table-column prop="i" fixed="left" label="序号" width="60">
					</el-table-column>
					<el-table-column label="图片" width="120">
						<template slot-scope="scope">
							<el-image :src="READ_IMG_URL + scope.row.image" style="width: 90px; height: 90px;"
								:preview-src-list="new Array(READ_IMG_URL + scope.row.image)">
							</el-image>
						</template>
					</el-table-column>
					<el-table-column prop="partName" label="零件名称" fit>
					</el-table-column>
					<el-table-column prop="model" label="零件型号" fit>
					</el-table-column>
					<el-table-column prop="purchasePrice" label="采购单价" width="100">
					</el-table-column>
					<el-table-column prop="freight" label="运输费" width="100">
					</el-table-column>
					<el-table-column prop="isIncludeTax" label="是否含税" width="100">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.isIncludeTax === 0">含税</el-tag>
							<el-tag v-if="scope.row.isIncludeTax === 1" type="danger">
								不含税
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="partCount" label="采购数量" width="100">
					</el-table-column>
					<el-table-column prop="totalPrice" label="总计" width="100">
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>
		<!-- 付款弹窗 -->
		<el-dialog style="margin-top:0" :visible.sync="paymentShow" width="75%" title="付款" @close="paymentClose">
			<div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
				<div>
					<label>{{ `总计金额：${totalAmount}` }}</label>
				</div>
				<el-select v-model="accountId" filterable remote clearable placeholder="选择付款账户" style="width: 200px;"
					:loading="selectLoading" :remote-method="getAccountList" @focus="getAccountList('')">
					<el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id">
					</el-option>
				</el-select>
			</div>
			<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%;" :max-height="400">
				<el-table-column prop="i" label="序号" width="60">
				</el-table-column>
				<el-table-column prop="userName" label="采购人" fit>
				</el-table-column>
				<el-table-column prop="price" label="总金额" fit>
				</el-table-column>
				<el-table-column prop="orderTime" label="下单时间" fit>
				</el-table-column>
				<el-table-column prop="amountPayable" label="付款金额" fit>
				</el-table-column>
				<el-table-column prop="datePayable" label="付款日期" fit>
				</el-table-column>
			</el-table>
			<span slot="footer" class="dialog-footer">
				<el-button @click="paymentShow = false">取消</el-button>
				<el-button type="primary" @click="payment">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import warehouseApi from '../../../api/warehouse';
import financeApi from '../../../api/financeManage';
import config from '../../../api/apiURL.js';
export default {
	data() {
		return {
			userInfo: null,
			READ_IMG_URL: config.READ_IMG_URL,
			supplier: {
				id: null,
				suppliersName: null
			},
			tableData: [],
			loading: false,
			selectLoading: false,
			currentPage: 1,
			pageSize: 50,
			total: 0,
			paymentMethod: null,
			selectDate: null,
			yearMonth: null,
			radio: 1,
			selectDateList: [],
			paymentShow: false,
			totalAmount: 0.00,
			accountList: [],
			accountId: null,
			partsShow: false,
			selectTitle: "",
			selectPurchase: {},
			MtotalAmount: 0
		}
	},
	created() {
		this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
		// 初始化日期
		this.initializeDate();
		const id = localStorage.getItem("supplierId");
		if (id) {
			this.supplier.id = id
			this.getSupplier();
		} else {
			this.toBack();
		}
	},
	destroyed() {
		localStorage.removeItem("supplierId");
	},
	methods: {
		// 返回上个页面
		toBack() {
			this.$router.push({
				path: "/warehouse/supplier/supplier"
			})
		},
		// 初始化日期
		initializeDate() {
			const currentYear = new Date().getFullYear();
			let currentMonth = new Date().getMonth() + 1;
			let currentDay = new Date().getDate()
			currentMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth;
			currentDay = currentDay < 10 ? '0' + currentDay : currentDay;
			this.yearMonth = `${currentYear}-${currentMonth}`
			this.selectDate = this.yearMonth;
		},
		// 日期改变
		changeDate() {
			this.yearMonth = null;
			if (this.selectDate !== null) {
				const year = this.selectDate.getFullYear();
				const month = this.selectDate.getMonth() + 1; // 月份从 0 开始，需要加 1
				const day = this.selectDate.getDate();
				// 格式化月份和日期，确保始终是两位数
				const formattedMonth = month < 10 ? '0' + month : month;
				const formattedDay = day < 10 ? '0' + day : day;
				this.yearMonth = `${year}-${formattedMonth}`;
			}
			this.getSupplierBilling();
		},
		// 获取供应商
		getSupplier() {
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			warehouseApi.getSuppliers(this.supplier).then(res => {
				if (res.code === 200) {
					this.supplier = res.data;
					this.getSupplierBilling();
				}
			}).finally(() => {
				loading.close();
			})
		},
		// pageSize变化
		handleSizeChange(pageSize) {
			this.pageSize = pageSize
			this.getSupplierBilling()
		},
		// 页码变化
		handleCurrentChange(curPage) {
			this.currentPage = curPage
			this.getSupplierBilling()
		},
		// 获取供应商账单
		getSupplierBilling() {
			this.loading = true;
			const data = {
				payee: this.supplier.id,
				currentPage: this.currentPage,
				pageSize: this.pageSize,
				paymentMethod: this.paymentMethod,
				yearMonth: this.yearMonth
			}
      this.tableData = [];
			financeApi.getSupplierBilling(data).then(res => {
				if (res.code === 200) {
					this.total = res.data.total;
					this.MtotalAmount = res.data.MtotalAmount
					this.tableData = res.data.paymentBillingList.map((item, index) => {
						item.i = (this.currentPage - 1) * this.pageSize + index + 1;
						return item;
					})
				}
			}).finally(() => {
				this.loading = false;
			})
		},
		// 展示零件列表
		partsOpen(row) {
			row.parts.forEach((part, index) => {
				part.i = index + 1
			})
			this.selectPurchase = row;
			this.selectTitle = row.userName;
			this.partsShow = true;
		},
		// 关闭零件列表
		partsClose() {
			this.selectPurchase = {}
			this.selectTitle = ""
		},
		// 单选改变
		radioChange(e) {
			if (e === 1) {
				this.paymentMethod = 1
			} else {
				this.paymentMethod = null
			}
			this.getSupplierBilling();
		},
		// 多选账单
		handleSelectionChange(e) {
			this.selectDateList = e;
		},
		// 打开付款弹窗
		paymentDialog() {
			if (this.selectDateList.length < 1) {
				this.$message.error("请选择账单");
				return;
			}
			this.selectDateList.forEach(item => {
				this.totalAmount = this.totalAmount + item.amountPayable
			})
			this.paymentShow = true;
		},
		// 关闭付款弹窗
		paymentClose() {
			this.totalAmount = 0.00;
		},
		// 远程搜索账户
		getAccountList(query) {
			this.selectLoading = true;
			const data = {
				accountName: query,
				currentPage: 1,
				pageSize: 10,
			}
			financeApi.getAccountList(data).then(res => {
				if (res.code === 200) {
					this.accountList = res.data.accountList
				}
			}).finally(() => {
				this.selectLoading = false;
			})
		},
		// 付款
		payment() {
			if (this.accountId === null) {
				this.$message.error("请选择付款账户");
				return;
			}
			this.$confirm('确定要付款吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				const loading = this.$loading({
					lock: true,
					text: '付款中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				let idList = this.selectDateList.map(item => {
					const id = item.id;
					return id;
				})
				const data = {
					idList: idList,
					account: this.accountId
				}
				financeApi.paymentSupplierBilling(data).then(res => {
					if (res.code === 200) {
						this.$message.success("付款成功！")
						this.getSupplierBilling();
            this.$refs.multipleTable.clearSelection();
						this.paymentShow = false;
					}
				}).finally(() => {
					loading.close();
				})
			})
		},
		// 重置
		reset() {
			this.selectDate = new Date;
			this.changeDate();
		},
		selectable(row) {
      // console.log(row.billsStatus !== 0);
			return row.billsStatus === 0;
		}
	}
}
</script>

<style>
.supplier-billing {
	height: 100%;
}

.data-table {
	height: 87%;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	justify-content: center;
	margin-top: 10px;
}
</style>